﻿/*
Copyright (c) 2007-2011 William POTTIER - AllProgrammic

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights 
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 
of the Software, and to permit persons to whom the Software is furnished to do so, 
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all 
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;

namespace NetAccess.Utils
{
    /// <summary>
    /// Manage the encryption
    /// </summary>
    public static class EncryptionManager
    {
        /// <summary>
        /// Generate asymetric key (RSA)
        /// </summary>
        /// <param name="publicKey">Generated public key</param>
        /// <param name="privateKey">Generated private key</param>
        public static void GenerateKeyPair(out byte[] publicKey, out byte[] privateKey)
        {
            var rsa = new RSACryptoServiceProvider();
            publicKey = rsa.ExportCspBlob(false);
            privateKey = rsa.ExportCspBlob(true);
        }

        /// <summary>
        /// Translate byte array key in string key
        /// </summary>
        /// <param name="key">key in byte array</param>
        /// <returns>key in string</returns>
        public static string ConvertKeyToString(byte[] key)
        {
            return key != null ? Convert.ToBase64String(key) : null;
        }

        /// <summary>
        /// Translate string key in byte array key
        /// </summary>
        /// <param name="key">key in string</param>
        /// <returns>key in byte array</returns>
        public static byte[] ConvertKeyFromString(string key)
        {
            return Convert.FromBase64String(key);
        }

        internal static byte[] Crypt(byte[] publicKey, byte[] data)
        {
            var ms = new MemoryStream();

            var rij = Rijndael.Create();
            var symKey = rij.Key;

            var rsa = new RSACryptoServiceProvider();
            rsa.ImportCspBlob(publicKey);
            var cryptedkey = rsa.Encrypt(symKey, false);
            ms.Write(cryptedkey, 0, cryptedkey.Length);

            var iv = new byte[16];
            var cs = new CryptoStream(ms, rij.CreateEncryptor(symKey, iv), CryptoStreamMode.Write);
            cs.Write(data, 0, data.Length);
            cs.FlushFinalBlock();

            return ms.ToArray();
        }

        internal static byte[] Decrypt(byte[] privateKey, byte[] data)
        {
            var ms = new MemoryStream();

            var buffer = new List<byte>(data);
            var cryptedKey = buffer.GetRange(0, 128).ToArray();
            var content = buffer.GetRange(128, data.Length - 128).ToArray();

            var rsa = new RSACryptoServiceProvider();
            rsa.ImportCspBlob(privateKey);
            var symKey = rsa.Decrypt(cryptedKey, false);

            var iv = new byte[16];
            var rij = Rijndael.Create();
            var cs = new CryptoStream(ms, rij.CreateDecryptor(symKey, iv), CryptoStreamMode.Write);
            cs.Write(content, 0, content.Length);
            cs.FlushFinalBlock();

            return ms.ToArray();
        }
    }
}
